package com.esunny.springboot.controller;

import com.esunny.springboot.pojo.domain.R;
import com.esunny.springboot.pojo.dto.LoginBody;
import com.esunny.springboot.pojo.dto.LoginUser;
import com.esunny.springboot.service.UserService;
import com.esunny.springboot.service.impl.TokenService;
import com.esunny.springboot.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@Api(value = "用户登录登出和刷新token", tags = {"会话相关的api"})
@RequestMapping("/user")
@RestController
public class TokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserService userService;

    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping("/login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = userService.login(form.getUsername(), form.getPassword());
        // 生成token返回
        return R.ok(tokenService.createToken(userInfo));
    }

    @ApiOperation(value = "登出", notes = "登出")
    @DeleteMapping("/logout")
    public R<?> logout(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            userService.logout(username);
        }
        return R.ok(null, "用户退出成功");
    }

    @ApiOperation(value = "刷新token", notes = "刷新token")
    @PostMapping("/refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
        } else {
            return R.fail("token失效");
        }
        return R.ok(null, "令牌刷新成功");
    }
}
